package net_app.bs;

import net_app.socket3.ServerReaderThread;
import net_app.tcp_sms.ServerDemo1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class BSServerDemo {
    private static ExecutorService pool = new ThreadPoolExecutor(3,5,6, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        try {
            System.out.println("==========服务端启动成功========");
            // 1.注册端口
            ServerSocket serverSocket = new ServerSocket(8080);
            // 定义一个死循环由主线程负责不断的接收客户端的socket管道连接
            while (true) {
                // 2.每接收到一个客户端的Socket管道,交给一个独立的子线程负责读消息
                Socket socket = serverSocket.accept();
                System.out.println(socket.getRemoteSocketAddress() + "上线了");
                pool.execute(new ServerReaderThread(socket));
            }

        } catch (IOException e) {
            e.getStackTrace();
        }
    }
    public static class ServerReaderRunnable extends Thread {
        private Socket socket;
        public ServerReaderRunnable(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                // 浏览器已经与本线程建立了Socket连接
                // 响应消息给浏览器显示
                PrintStream ps = new PrintStream(socket.getOutputStream());
                // 必须想要HTTP协议格式数据，否则浏览器不识别消息
                ps.println("HTTP/1.1 200 OK"); // 协议类型和版本，响应成功的消息！
                ps.println("Content-Type:text/html;charset=UTF-8"); // 响应的数据类型：文本/网页
                ps.println(); // 必须发一个空行
                // 不可以响应数据回去给浏览器
                ps.println("<span style='color:#21d1f'> 奈奈子 </span>");
                ps.close();
            } catch (IOException e) {
                System.out.println(socket.getRemoteSocketAddress() + "下线了");
                ServerDemo1.allOnlineSocket.remove(socket);
            }
        }
    }
}
